import React, { Component } from 'react';
import { Card, Table, Button, message, Select } from 'antd';
import { connect } from 'dva';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import moment from 'moment';
import styles from './index.less';
import router from 'umi/router';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import { filterAuth } from '@/support/common';
import { PlusOutlined } from '@ant-design/icons';
import Ellipsis from '../../../components/Ellipsis';

const FuncTypeHash = {
  '1': 'APP功能',
  '2': '车机功能',
  '3': '算法',
  '4': '车辆健康',
};
const mapStateToProps = (state: any) => ({
  functionConfig: state.functionConfig,
  loading: state.loading.models['functionConfig'],
  menu: state.menu,
});
class FunctionConfig extends Component<any, any> {
  state = {
    postUrl: '',
    formValues: {},
    pageParams: {
      pageNo: 1,
      pageSize: 10,
    },
    seriesOptions: [],
    vehicleTypeOptions: [],
    brandOptions: [],
    defaultBrand: '',
    selectBrand: '',
  };

  componentDidMount() {
    const { dispatch } = this.props;
     //获取品牌数据
     dispatch({
      type: 'basedata/brandFetch',
      callback: (res:any) => {
        this.setState({ 
           brandOptions: res?.data,
          });
          if(this.props.location.state&&this.props.location.state.sourceRouter == 'functionConfig'){
            const brandData = JSON.parse(sessionStorage.getItem('functionConfigBrandInfo')||'{}');
            const brandId = brandData&&brandData?.selectBrand
            this.setState({ 
              defaultBrand: brandId,
              selectBrand: brandId
             });
             this.getSeriesData(brandId);
             this.handleFreshPage(brandId);
          }else{
            this.setState({ 
              defaultBrand: res?.data[0].brandCode,
              selectBrand: res?.data[0].brandCode
             });
          this.getSeriesData(res?.data[0].brandCode);
          this.handleFreshPage(res?.data[0].brandCode);
          }
        }
    });
    // this.getSeriesData();
    // this.handleFreshPage();
  }
  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'functionConfig/initData',
    });
  }
  /**
   * 获取车系下拉数据
   */
  getSeriesData = (brandId:String) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'functionConfig/getFetchPage',
      payload: {
        url: '/msdevice/base/vehicle/series/bybrand/list',
        brandId
      },
      callback: (resp: any) => {
        const data = resp.data;
        this.setState({
          seriesOptions: data.map((item: { seriesCode: any; seriesName: any }) => {
            return {
              value: item.seriesCode,
              label: item.seriesName,
            };
          }),
        });
      },
    });
  };

  /**
   * 获取车型组数据
   */
  getVehicleTypeData = (seriesCode: string) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'functionConfig/postData',
      payload: {
        url: '/vehicle/group/findBySeriesCode',
        seriesCode,
      },
      callback: (resp: any) => {
        const data = resp.data;
        this.setState({
          vehicleTypeOptions: data.map((item: any) => {
            return {
              value: item.sid,
              label: item.name,
            };
          }),
        });
      },
    });
  };
  handleFreshPage = (brandId:string) => {
    const { dispatch } = this.props;
    const { formValues, pageParams } = this.state;
    dispatch({
      type: 'functionConfig/fetchPageData',
      // type: 'functionConfig/queryList',
      payload: {
        url: '/vehicle/functionConfig/findList',
        brandId:brandId,
        ...formValues,
        ...pageParams,
      },
    });
  };

  handleFormReset = () => {
    this.searchForm?.current.setFieldsValue({});
    this.setState({
      formValues: {},
      pageParams: {
        pageNo: 1,
        pageSize: 10,
      },
    });
  };
  // 分页时触发
  tableOnChange = (pagination: any) => {
    const {selectBrand } = this.state;
    const current = pagination.current;
    this.setState(
      {
        pageParams: {
          pageNo: current,
          pageSize: pagination.pageSize,
        },
      },
      () => {
        this.handleFreshPage(selectBrand);
      },
    );
  };

  /**
   * 删除
   * @param sid
   */
  handleDelete = (sid: any) => {
    const { dispatch } = this.props;
    const {selectBrand } = this.state;
    // console.log(data);
    dispatch({
      type: 'functionConfig/postData',
      // type: 'functionConfig/del',
      payload: {
        url: `/vehicle/functionConfig/delete/${sid}`,
      },
      callback: (response: any) => {
        if (response && response.statusCode == '0') {
          message.success('操作成功！');
          this.handleFreshPage(selectBrand);
        } else {
          message.error(response.statusMessage);
        }
      },
    });
  };

  /**
   * 新增
   */
  handleAdd = () => {
    const { formValues, selectBrand } = this.state;
    const searchValues = {
      ...formValues,
      selectBrand
    };
    sessionStorage.setItem('functionConfigBrandInfo', JSON.stringify(searchValues));
    router.push(`/remoteConfiguration/functionConfig/functionConfigAdd?brandId=${selectBrand}`,);
  };

  /**
   * 编辑
   * @param sid
   * @param vehicleSerieId
   */
  handleEdit = (sid: String, vehicleSerieId: String) => {
    const { formValues, selectBrand } = this.state;
    const searchValues = {
      ...formValues,
      selectBrand
    };
    sessionStorage.setItem('functionConfigBrandInfo', JSON.stringify(searchValues));
    router.push(`/remoteConfiguration/functionConfig/functionConfigEdit?id=${sid}&seriesCode=${vehicleSerieId}&brandId=${selectBrand}`,);
  };
  onBrandSelect = (value:any) =>{
    this.setState({
      selectBrand: value,
      formValues: {},
    },()=>{
      this.searchForm.current.resetFields();
      this.getSeriesData(value);
      this.handleFreshPage(value);
    })
  };
  render() {
    const {
      location: { pathname = '/' },
      loading,
      functionConfig: {
        pageList: { list = [], pagination },
      },
      menu: { permissions },
    } = this.props;

    const { formValues, seriesOptions, vehicleTypeOptions, pageParams,brandOptions,defaultBrand, selectBrand } = this.state;
    const options = brandOptions.map((item:any)=>{
      return {
        label: item.brandName,
        value: item.brandCode
      }
    })
    const columns: Array<any> = [
      {
        title: '车系',
        dataIndex: 'vehicleSeries',
      },
      {
        title: '车型组',
        dataIndex: 'vehicleTypeGroup',
      },
      {
        title: '功能', //  一级配置项
        dataIndex: 'functionItem',
        render: (text: any, data: any) => {
          return data?.function
            ?.map((func: any) => {
              return `${FuncTypeHash[func.functionConfigType]}: ${func.functionItems}`;
            })
            .join('\n');
        },
      },
      {
        title: '备注',
        dataIndex: 'remark',
        render: (val: any) => (
          <Ellipsis length={24} tooltip>
            {val}
          </Ellipsis>
        ),
      },
      {
        title: '操作人',
        dataIndex: 'createBy',
      },
      {
        title: '创建时间',
        dataIndex: 'createDate',
        render: (text: any) => {
          return text && moment(text).format('YYYY-MM-DD HH:mm:ss');
        },
      },
      {
        title: '操作',
        dataIndex: '操作',
        key: 'opt',
        width: 150,
        fixed: 'right',
        render: (text: any, data: any) => {
          const btns = [
            {
              title: '编辑',
              key: 'edit',
              auth: 'functionConfig_edit',
              onConfirm: (e: any) => {
                e.stopPropagation();
                this.handleEdit(data?.sid, data?.vehicleSerieId);
              },
            },
            {
              title: '删除',
              key: 'del',
              auth: 'functionConfig_delete',
              message: '是否确认删除？',
              Popconfirm: true,
              onConfirm: () => this.handleDelete(data.sid),
            },
          ];
          return <PateoAuthButtons btns={btns} max={1} pathname={pathname} />;
        },
      },
    ];

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };

    const searchItems = [
      {
        title: '车系',
        type: 'select',
        customStyle: 6,
        selectOptions: seriesOptions,
        onSelectChange: (seriesCode: string) => {
          this.searchForm?.current.setFieldsValue({ vehicleTypeGroup: null });
          seriesCode
            ? this.getVehicleTypeData(seriesCode)
            : this.setState({ vehicleTypeOptions: [] });
        },
        key: 'vehicleSeries',
      },
      {
        title: '车型组',
        type: 'select',
        customStyle: 6,
        selectOptions: vehicleTypeOptions,
        key: 'vehicleTypeGroup',
      },
    ];
    return (
      <div>
        <div  style={{margin: '0px 10px 10px 10px'}}>
          <div style={{display:'inline-block'}}>
          <span>品牌：</span>
          </div>
          <div style={{display:'inline-block'}}>
              <Select
                allowClear={false}
                placeholder="请选择品牌"
                getPopupContainer={(triggerNode) => triggerNode.parentNode}
                    
                onChange={this.onBrandSelect}
                style={{width: '250px'}}
                key={defaultBrand}
                defaultValue={defaultBrand}
                options={options}
              >
              </Select>
          </div>
        </div>
      <div className={styles.container}>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            fetchParams={{
              type: 'functionConfig/fetchPageData',
              url: '/vehicle/functionConfig/findList',
              // extraArgs: {
              //   ...pageParams,
              // },
            }}
            extraArgs={{ brandId: selectBrand, ...pageParams,}}
            saveFormValues={(val: any) =>
              this.setState({
                formValues: Object.assign(formValues, val),
              })
            }
            handleFormReset={this.handleFormReset}
          />
        </Card>
        <Card title="" bordered={false}>
          {filterAuth('functionConfig_add', permissions, pathname) ? (
            <div className="my_newItem">
              <Button
                size="small"
                icon={<PlusOutlined />}
                type="primary"
                onClick={() => this.handleAdd()}
              >
                新增
              </Button>
            </div>
          ) : null}
          <Table
            className={styles['customer-grid']}
            loading={loading}
            rowKey={row => row.sid}
            columns={columns}
            size="small"
            pagination={paginationProps}
            dataSource={list}
            onChange={this.tableOnChange}
            scroll={{ x: true }}
          />
        </Card>
      </div>
      </div>
    );
  }
}
export default connect(mapStateToProps)(FunctionConfig);
